﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;

namespace NetWorkSet
{
    public partial class SETControl : UserControl
    {
        public SETControl()
        {
            InitializeComponent();
        }
        SetHelper sh = new SetHelper();
        XmlDocument xmlDoc = new XmlDocument();
        private void SETControl_Load(object sender, EventArgs e)
        {
            if (radioButton1.Checked == true)
            {
                //锁定按钮方法
                this.ControlLock(false);
                this.DNSControlLock(false);
            }
            //绑定网卡名称到列表（用于显示）
            if (sh.GetNicNameShow()[0] != "")
            {
                this.comboBox1.DataSource = sh.GetNicNameShow();
                this.comboBox2.DataSource = sh.GetNicName();
            }
            //绑定网卡名称到列表（隐藏）


        }
        /// <summary>
        /// IP控件失去焦点事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ipControl1_Leave(object sender, EventArgs e)
        {
            if (this.ipControl1.txtisNull())
            {
                //自动生成子网掩码
                switch (this.ipControl1.Type.ToString())
                {
                    case "A":
                        this.subnetMaskControl1.SetTextBox("255.0.0.0");
                        break;
                    case "B":
                        this.subnetMaskControl1.SetTextBox("255.255.0.0");
                        break;
                    case "C":
                        this.subnetMaskControl1.SetTextBox("255.255.255.0");
                        break;
                    case "D":
                        this.subnetMaskControl1.SetTextBox("255.255.255.255");
                        break;
                }
                //自动生成默认网关
                this.ipControl2.SetWay(this.ipControl1.GeteWay());
                //this.btnSubmit.Focus();
                this.ipControl3.Focus();
            }
            //else
            //{
            //    this.subnetMaskControl1.Focus();
            //}
        }

        /// <summary>
        /// 子网掩码失去焦点事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void subnetMaskControl1_Leave(object sender, EventArgs e)
        {
            if (this.ipControl1.txtisNull())
            {
                //自动生成默认网关
                this.ipControl2.SetWay(this.ipControl1.GeteWay());
                //this.btnSubmit.Focus();
                this.ipControl3.Focus();
            }
            //else
            //{
            //    this.ipControl2.Focus();
            //}
        }

        /// <summary>
        /// 自动获取IP地址按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton1.Checked == true)
            {
                //清空文本框
                this.ipControl1.txtClear();
                this.ipControl2.txtClear();
                this.subnetMaskControl1.txtClear();
                //锁定按钮方法
                this.ControlLock(false);
            }
        }

        /// <summary>
        /// 手动设置IP地址按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton2.Checked == true)
            {
                //锁定按钮方法
                this.ControlLock(true);
                this.radioButton4.Checked = true;
                this.ipControl1.Focus();
            }
        }

        private void radioButton3_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton3.Checked == true)
            {
                //清空文本框
                this.ipControl3.txtClear();
                //锁定按钮方法
                this.DNSControlLock(false);
            }
        }

        private void radioButton4_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton4.Checked == true)
            {
                //锁定按钮方法
                this.DNSControlLock(true);
                this.ipControl3.Focus();
            }
        }

        /// <summary>
        /// IP控件锁定方法
        /// </summary>
        /// <param name="bl"></param>
        private void ControlLock(bool bl)
        {
            this.ipControl1.Enabled = bl;
            this.ipControl2.Enabled = bl;

            this.subnetMaskControl1.Enabled = bl;
            //this.btnClear.Enabled = bl;
            //this.btnSubmit.Enabled = bl;
            this.button1.Enabled = bl;
            this.button2.Enabled = bl;
            this.button3.Enabled = bl;

        }

        /// <summary>
        /// DN控件锁定方法
        /// </summary>
        /// <param name="bl"></param>
        private void DNSControlLock(bool bl)
        {
            this.ipControl3.Enabled = bl;
            this.button4.Enabled = bl;
        }

        /// <summary>
        /// 清空文本方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void btnClear()
        {
            //清空文本框
            this.ipControl1.txtClear();
            this.ipControl2.txtClear();
            this.ipControl3.txtClear();
            this.subnetMaskControl1.txtClear();
            this.ipControl1.Focus();
        }

        /// <summary>
        /// 获取本机IP地址
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            this.ipControl1.SetTextBox(sh.GetLocalAddress(this.comboBox2.Text, "IPAddress"));
            this.ipControl1.Focus();
        }

        /// <summary>
        /// 获取本机子网掩码地址
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            this.subnetMaskControl1.SetTextBox(sh.GetLocalAddress(this.comboBox2.Text, "IPSubnet"));
            this.subnetMaskControl1.Focus();
        }

        /// <summary>
        /// 获取本机默认网关地址
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            this.ipControl2.SetTextBox(sh.GetLocalAddress(this.comboBox2.Text, "DefaultIPGateway"));
            this.ipControl2.Focus();
        }

        /// <summary>
        /// 获取本机默认DNS服务器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            this.ipControl3.SetTextBox(sh.GetLocalAddress(this.comboBox2.Text, "DNSServerSearchOrder"));
            this.ipControl3.Focus();
        }

        //DNSServerSearchOrder //DNS参数名

        /// <summary>
        /// 应用方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void btnSubmit()
        {
            //判断IP/掩码/网关
            if (this.radioButton1.Checked == true)
            {
                //切换为自动获取IP
                sh.setIPAuto();
            }
            if (this.radioButton3.Checked == true)
            {
                //切换为自动获取DNS
                sh.SetDNSAuto();
            }
            if (this.radioButton2.Checked == true)
            {
                if (this.ipControl1.txtisNull() && this.subnetMaskControl1.txtisNull() && this.ipControl2.txtisNull())
                    this.SetSubmit();
                else
                {
                    ShowMessage("提示", "文本框中有空缺值！");
                    return;
                }
                //if (MessageBox.Show("文本框中有空缺值，是否继续执行修改？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk).ToString() == "Yes")
                //    this.SetSubmit();
            }
            if (this.radioButton4.Checked == true)
            {
                if (this.ipControl3.txtisNull())
                    //设置DNS服务器
                    //sh.SetDNS(this.ipControl3.GetTextValuePra());
                    sh.SetIPAddress(this.comboBox2.Text, null, null, null, this.ipControl3.GetTextValuePra());
                else
                {
                    ShowMessage("提示", "IP地址修改成功，但DNS文本框中有空缺值！");
                    return;
                }
            }
            //修改成功提示
            ShowMessage("提示", "修改成功");
        }

        /// <summary>
        /// 执行修改IP/掩码/网关方法
        /// </summary>
        private void SetSubmit()
        {
            string[] Str = new string[4];

            if (this.ipControl1.txtisNull())
                Str[0] = this.ipControl1.GetTextValueStr();
            else
                Str[0] = null;

            if (this.subnetMaskControl1.txtisNull())
                Str[1] = this.subnetMaskControl1.GetTextValueStr();
            else
                Str[1] = null;

            if (this.ipControl2.txtisNull())
                Str[2] = this.ipControl2.GetTextValueStr();
            else
                Str[2] = null;

            if (this.ipControl3.txtisNull())
                Str[3] = this.ipControl3.GetTextValueStr();
            else
                Str[3] = null;

            sh.SetIPAddress(this.comboBox2.Text, new string[] { Str[0] }, new string[] { Str[1] }, new string[] { Str[2] }, new string[] { Str[3] });


        }


        /// <summary>
        /// 弹出框
        /// </summary>
        /// <param name="title">标题</param>
        /// <param name="txt">文本</param>
        private void ShowMessage(string title, string txt)
        {
            MessageBox.Show(this, txt, title);
        }

        /// <summary>
        /// 读取本机设置按钮
        /// </summary>
        private void button5_Click(object sender, EventArgs e)
        {
            this.radioButton2.Checked = true;
            this.radioButton4.Checked = true;
            this.ipControl1.SetTextBox(sh.GetLocalAddress(this.comboBox2.Text, "IPAddress"));
            this.subnetMaskControl1.SetTextBox(sh.GetLocalAddress(this.comboBox2.Text, "IPSubnet"));
            this.ipControl2.SetTextBox(sh.GetLocalAddress(this.comboBox2.Text, "DefaultIPGateway"));
            this.ipControl3.SetTextBox(sh.GetLocalAddress(this.comboBox2.Text, "DNSServerSearchOrder"));
            this.ipControl1.Focus();
        }

        ////创建一个XML对象
        //XmlDocument xmlDoc;

        ////定义一个结点对象
        //XmlNode node;

        ////获取当前工作目录路径
        //string workDir = Directory.GetCurrentDirectory();

        ////List<Student> stuList = new List<Student>();


        ////定义一个元素
        //XmlElement xmlEle;


        /// <summary>
        /// 保存配置到XML
        /// </summary>
        public void btnSave(string SetName, string SetText)
        {
            #region 获取文本框内容
            //获取文本框内容
            string[] Str = new string[4];

            if (this.ipControl1.txtisNull())
                Str[0] = this.ipControl1.GetTextValueStr();
            else
                Str[0] = null;

            if (this.subnetMaskControl1.txtisNull())
                Str[1] = this.subnetMaskControl1.GetTextValueStr();
            else
                Str[1] = null;

            if (this.ipControl2.txtisNull())
                Str[2] = this.ipControl2.GetTextValueStr();
            else
                Str[2] = null;

            if (this.ipControl3.txtisNull())
                Str[3] = this.ipControl3.GetTextValueStr();
            else
                Str[3] = null;
            #endregion

            #region 写入XML文件

            try
            {
                xmlDoc.Load("NETWORKSET.xml");
            }
            catch (Exception)
            {
                XmlTextWriter writer = new XmlTextWriter("NETWORKSET.xml", System.Text.Encoding.UTF8);

                //使用自动缩进便于阅读
                writer.Formatting = Formatting.Indented;
                writer.WriteStartElement("NETWORKSET");
                writer.Close();
                xmlDoc.Load("NETWORKSET.xml");
            }

            XmlNodeList nodeList = xmlDoc.SelectSingleNode("NETWORKSET").ChildNodes;//获取bookstore节点的所有子节点
            XmlNode root = xmlDoc.SelectSingleNode("NETWORKSET");
            int XmlCount = 0;

            //foreach (XmlNode xn in nodeList)//遍历所有子节点
            //{
            //root = xmlDoc.SelectSingleNode("NETWORKSET");//查找<NETWORKSET>
            XmlCount = root.SelectNodes(SetName).Count; //查找该标签页的设置是否存在，大于0则存在
            //}

            //判断如果XMLCOUNT等于0，则说明没有该节点，则追加进去
            #region 追加节点
            if (XmlCount == 0)
            {
                root = xmlDoc.SelectSingleNode("NETWORKSET");//查找<NETWORKSET>
                XmlElement xe1 = xmlDoc.CreateElement(SetName);//创建一个<book>节点
                xe1.SetAttribute("NAME", SetName);//设置该节点属性及属性值
                xe1.SetAttribute("TEXT", SetText);//设置该节点属性及属性值

                if (this.radioButton1.Checked == true)
                {
                    XmlElement xesub1 = xmlDoc.CreateElement("AUTO_IP");
                    xesub1.InnerText = "0";//设置文本节点
                    xe1.AppendChild(xesub1);//添加到<book>节点中

                    XmlElement xesub2 = xmlDoc.CreateElement("IP_ADDRESS");
                    xesub2.InnerText = "";//设置文本节点
                    xe1.AppendChild(xesub2);//添加到<book>节点中

                    XmlElement xesub3 = xmlDoc.CreateElement("IP_ZWYM");
                    xesub3.InnerText = "";//设置文本节点
                    xe1.AppendChild(xesub3);//添加到<book>节点中

                    XmlElement xesub4 = xmlDoc.CreateElement("IP_MRWG");
                    xesub4.InnerText = "";//设置文本节点
                    xe1.AppendChild(xesub4);//添加到<book>节点中
                }
                else
                {
                    XmlElement xesub1 = xmlDoc.CreateElement("AUTO_IP");
                    xesub1.InnerText = "1";//设置文本节点
                    xe1.AppendChild(xesub1);//添加到<book>节点中

                    XmlElement xesub2 = xmlDoc.CreateElement("IP_ADDRESS");
                    xesub2.InnerText = Str[0];//设置文本节点
                    xe1.AppendChild(xesub2);//添加到<book>节点中

                    XmlElement xesub3 = xmlDoc.CreateElement("IP_ZWYM");
                    xesub3.InnerText = Str[1];//设置文本节点
                    xe1.AppendChild(xesub3);//添加到<book>节点中

                    XmlElement xesub4 = xmlDoc.CreateElement("IP_MRWG");
                    xesub4.InnerText = Str[2];//设置文本节点
                    xe1.AppendChild(xesub4);//添加到<book>节点中
                }

                if (this.radioButton3.Checked == true)
                {
                    XmlElement xesub5 = xmlDoc.CreateElement("AUTO_DNS");
                    xesub5.InnerText = "0";//设置文本节点
                    xe1.AppendChild(xesub5);//添加到<book>节点中

                    XmlElement xesub6 = xmlDoc.CreateElement("DNS_SX");
                    xesub6.InnerText = "";//设置文本节点
                    xe1.AppendChild(xesub6);//添加到<book>节点中

                    XmlElement xesub7 = xmlDoc.CreateElement("DNS_BX");
                    xesub7.InnerText = "";//设置文本节点
                    xe1.AppendChild(xesub7);//添加到<book>节点中
                }
                else
                {
                    XmlElement xesub5 = xmlDoc.CreateElement("AUTO_DNS");
                    xesub5.InnerText = "1";//设置文本节点
                    xe1.AppendChild(xesub5);//添加到<book>节点中

                    XmlElement xesub6 = xmlDoc.CreateElement("DNS_SX");
                    xesub6.InnerText = Str[3];//设置文本节点
                    xe1.AppendChild(xesub6);//添加到<book>节点中

                    XmlElement xesub7 = xmlDoc.CreateElement("DNS_BX");
                    xesub7.InnerText = Str[3];//设置文本节点
                    xe1.AppendChild(xesub7);//添加到<book>节点中
                }

                root.AppendChild(xe1);//添加到<bookstore>节点中
                xmlDoc.Save("NETWORKSET.xml");
            }
            #endregion

            #region 修改XML
            else if (XmlCount == 1)
            {
                //删除原有节点
                //foreach (XmlNode xn in nodeList)
                //{
                XmlNode rt = root.SelectSingleNode(SetName);
                root.RemoveChild(rt);
                //}
                xmlDoc.Save("NETWORKSET.xml");

                //追加新的节点
                this.btnSave(SetName, SetText);
            }
            #endregion

            #region 报错（多个相同名称节点）
            else if (XmlCount > 1)
            {
                if (MessageBox.Show("配置文件中有" + XmlCount + "个名为<" + SetName + ">的配置，点击确定清除它们,\n并保存新的配置", "错误提示", MessageBoxButtons.OKCancel).ToString() == "OK")
                {

                    for (int i = 0; i < XmlCount; i++)
                    {
                        XmlNode rt = root.SelectSingleNode(SetName);
                        root.RemoveChild(rt);
                        xmlDoc.Save("NETWORKSET.xml");
                    }

                    //追加新的节点
                    this.btnSave(SetName, SetText);
                }
            }
            #endregion

            #endregion
        }

        //关于
        public void btnCare()
        {
            MessageBox.Show("谢谢使用！！！", "提示");
        }

        //修改标签名称按钮
        private void button6_Click(object sender, EventArgs e)
        {
            this.btnClear();
            //if ((this.ParentForm as Body).CheckListBox())
            //{
            //    MessageBox.Show("请选中一个要修改的配置项！","提示");
            //    return;
            //}
            //int selectNum = (this.ParentForm as Body).GetListBoxIndex();
            //GaiMing gm = new GaiMing((this.ParentForm as Body).GetListBoxName());
            //gm.ShowDialog();

            //DataSet ds = new DataSet();
            //ds.ReadXml("NETWORKSET.xml");

            //for (int i = 0; i < ds.Tables.Count; i++)
            //{
            //    if (ds.Tables[ds.Tables[i].TableName].Rows[0]["TEXT"].ToString() == this.Parent.Text)
            //    {
            //        this.Parent.Text = ds.Tables[ds.Tables[i].TableName].Rows[0]["TEXT"].ToString();
            //    }
            //}
            //this.Parent.Text = bd.SetTabName(bd.GetTabName());//修改窗体上标签名称
            //(this.ParentForm as Body).BindListBox(selectNum);
            //f1.DataLoad();//调用刷新方法
        }

        /// <summary>
        /// 获取XML数据
        /// </summary>
        /// <returns>所有数据</returns>
        public DataSet GetXMLNameList()
        {
            DataSet ds = new DataSet();
            try
            {
                ds.ReadXml("NETWORKSET.xml");
                return ds;
            }
            catch (Exception)
            {
                throw;
            }
        }

        //获取XML数据
        public string GetXMLData(string setName)
        {
            DataSet ds = new DataSet();
            string[] StrIp = new string[4];
            try
            {
                ds.ReadXml("NETWORKSET.xml");
                if (ds.Tables[setName].Rows[0]["AUTO_IP"].Equals("1"))
                {
                    //读取设置自动获取IP
                    this.radioButton2.Checked = true;
                    //读取设置IP地址
                    StrIp = ds.Tables[setName].Rows[0]["IP_ADDRESS"].ToString().Split('.');
                    this.ipControl1.SetTextBox(StrIp);
                    //读取设置子网掩码
                    StrIp = ds.Tables[setName].Rows[0]["IP_ZWYM"].ToString().Split('.');
                    this.subnetMaskControl1.SetTextBox(StrIp);
                    //读取设置默认网关
                    StrIp = ds.Tables[setName].Rows[0]["IP_MRWG"].ToString().Split('.');
                    this.ipControl2.SetTextBox(StrIp);
                }
                else
                {
                    this.radioButton1.Checked = true;
                }
                if (ds.Tables[setName].Rows[0]["AUTO_DNS"].Equals("1"))
                {
                    //读取设置默认网关
                    this.radioButton4.Checked = true;
                    StrIp = ds.Tables[setName].Rows[0]["DNS_SX"].ToString().Split('.');
                    this.ipControl3.SetTextBox(StrIp);
                }
                else
                {
                    this.radioButton3.Checked = true;
                }



                return ds.Tables[setName].Rows[0]["TEXT"].ToString();
            }
            catch (Exception)
            {
                return setName;
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            Form1 f1 = new Form1();
            this.Parent.Text = this.GetXMLData(f1.GetTabName());

        }
    }
}

